package com.hmall.trade.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hmall.client.cart.CartClient;
import com.hmall.client.item.dto.OrderDetailDTO;
import com.hmall.client.item.ItemClient;
import com.hmall.client.item.dto.ItemDTO;
import com.hmall.common.constants.MqConstants;
import com.hmall.common.exception.BadRequestException;
import com.hmall.common.utils.UserContext;
import com.hmall.trade.domain.dto.OrderFormDTO;
import com.hmall.trade.domain.po.Order;
import com.hmall.trade.domain.po.OrderDetail;
import com.hmall.trade.mapper.OrderMapper;
import com.hmall.trade.service.IOrderDetailService;
import com.hmall.trade.service.IOrderService;
import io.seata.spring.annotation.GlobalTransactional;
import lombok.RequiredArgsConstructor;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import java.time.LocalDateTime;
import java.util.*;
import java.util.stream.Collectors;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author 虎哥
 * @since 2023-05-05
 */
@Service
@RequiredArgsConstructor
public class OrderServiceImpl extends ServiceImpl<OrderMapper, Order> implements IOrderService {

    private final ItemClient itemClient;
    private final IOrderDetailService detailService;
   // private final CartClient cartClient;
    private final RabbitTemplate rabbitTemplate;


    @Override
    @GlobalTransactional
    public Long createOrder(OrderFormDTO orderFormDTO) {
        // 1.订单数据
        Order order = new Order();
        // 1.1.查询商品
        List<OrderDetailDTO> detailDTOS = orderFormDTO.getDetails();
        // 1.2.获取商品id和数量的Map
        Map<Long, Integer> itemNumMap = detailDTOS.stream()
                .collect(Collectors.toMap(OrderDetailDTO::getItemId, OrderDetailDTO::getNum));
        Set<Long> itemIds = itemNumMap.keySet();
        // 1.3.查询商品
        List<ItemDTO> items = itemClient.queryItemByIds(itemIds);
        if (items == null || items.size() < itemIds.size()) {
            throw new BadRequestException("商品不存在");
        }
        // 1.4.基于商品价格、购买数量计算商品总价：totalFee
        int total = 0;
        for (ItemDTO item : items) {
            total += item.getPrice() * itemNumMap.get(item.getId());
        }
        order.setTotalFee(total);
        // 1.5.其它属性
        order.setPaymentType(orderFormDTO.getPaymentType());
        order.setUserId(1L);
        order.setStatus(1);
        // 1.6.将Order写入数据库order表中,只访问本地数据库
        save(order);

        // 2.保存订单详情
        List<OrderDetail> details = buildDetails(order.getId(), items, itemNumMap);
        detailService.saveBatch(details);

        // 3.清理购物车商品
        //cartClient.deleteCartItemByIds(UserContext.getUser(),itemIds);
        Map<String, Object> map = Map.of("uid", UserContext.getUser(), "itemIds", itemIds);
        rabbitTemplate.convertAndSend(
                MqConstants.TRADE_EXCHANGE_NAME,
                MqConstants.TRADE_SUCCESS_KEY,
                map
        );
        // 4.扣减库存
        try {
            itemClient.deductStock(detailDTOS);
        } catch (Exception e) {
            throw new RuntimeException("库存不足！");
        }

        //5.延迟消息,当订单超时时,会对订单状态进行判断
        rabbitTemplate.convertAndSend(
                MqConstants.TRADE_EXCHANGE_NAME,
                MqConstants.TRADE_SUCCESS_KEY,
                order.getId(),
                message -> {
                    message.getMessageProperties().setDelay(1800000);
                    return message;
                });

        return order.getId();
    }


    @Override
    @Transactional
    public void cancelOrder(Long orderId) {
        // 1.取消订单
        lambdaUpdate()
                .set(Order::getStatus, 5)
                .set(Order::getCloseTime, LocalDateTime.now())
                .eq(Order::getId, orderId)
                .update();

        //2.恢复库存
        //查询订单明细
        List<OrderDetail> details = detailService.lambdaQuery()
                .eq(OrderDetail::getOrderId, orderId)
                .list();
        List<OrderDetailDTO> collect = details.stream().map(detail -> {
            OrderDetailDTO orderDetailDTO = new OrderDetailDTO();
            orderDetailDTO.setItemId(detail.getItemId());
            orderDetailDTO.setNum(detail.getNum() * -1);
            return orderDetailDTO;
        }).collect(Collectors.toList());

        itemClient.deductStock(collect);
    }

    //获取订单状态值
    @Override
    public Integer getStatus(Long orderId) {
        Order one = lambdaQuery().eq(Order::getId, orderId).select(Order::getStatus).one();
        return one.getStatus();
    }
    //更新订单表状态
    @Override
    public void setStatus(Long orderId, Integer status) {
        Order order = new Order();
        order.setId(orderId);
        order.setStatus(status);
        order.setPayTime(LocalDateTime.now());
        updateById(order);
    }

    //订单已支付
    @Override
    public void markOrderPaySuccess(Long orderId) {
       setStatus(orderId,2);
    }

    private List<OrderDetail> buildDetails(Long orderId, List<ItemDTO> items, Map<Long, Integer> numMap) {
        List<OrderDetail> details = new ArrayList<>(items.size());
        for (ItemDTO item : items) {
            OrderDetail detail = new OrderDetail();
            detail.setName(item.getName());
            detail.setSpec(item.getSpec());
            detail.setPrice(item.getPrice());
            detail.setNum(numMap.get(item.getId()));
            detail.setItemId(item.getId());
            detail.setImage(item.getImage());
            detail.setOrderId(orderId);
            details.add(detail);
        }
        return details;
    }
}
